<template>
    <div class="login-box">
        <div class="mobike"></div>
        <div class="agrnt-login">
            <div class="login-form">
                <Tabs value="name2">

                    <Tab-pane label="客服工作台" name="name2">
                        <Form :model="formAgent" ref="formAgent" :rules="agentRules">
                            <Form-item prop="user">
                                <Input v-model="formAgent.user" placeholder="工号" ></Input>
                            </Form-item>
                            <Form-item prop="password">
                                <Input v-model="formAgent.password" placeholder="密码" type="password"></Input>
                            </Form-item>
                            <!--<Form-item prop="extnum" v-show="extnumShow">-->
                                <!--<Input v-model="formAgent.extnum" placeholder="分机号"></Input>-->
                            <!--</Form-item>-->
                            <Form-item>
                                <!-- <Checkbox v-model="single">记住密码</Checkbox> -->
                                <Button type="error" long @click="loginBtn" :loading="loading2">
                                    <span v-if="!loading2">登录</span>
                                    <span v-else>正在登录...</span>
                                </Button>
                            </Form-item>
                        </Form>
                    </Tab-pane>
                    <Tab-pane label="管理控制台" name="name1">
                        <Form :model="formManagement" ref="formManagement" :rules="manageRules">
                            <Form-item prop="manageuser">
                                <Input v-model="formManagement.user" placeholder="工号"></Input>
                            </Form-item>
                            <Form-item prop="managepassword">
                                <Input v-model="formManagement.password" placeholder="密码" type="password"></Input>
                            </Form-item>
                            <Form-item>
                                <!-- <Checkbox v-model="single">记住密码</Checkbox> -->
                                <Button type="error" long @click="goto">登录</Button>
                            </Form-item>
                        </Form>
                    </Tab-pane>
                </Tabs>
            </div>
        </div>
    </div>
</template>

<script>
    import $ from "jquery";
    import loginService from "service/loginService.js";
    import jsCookie from 'js-cookie';

    export default {
        data() {
            return {
                getExtNum: "",
                formAgent: {
                    user: "",
                    password: "",
                    //                    extnum:
                    //                      localStorage.getItem("UserMsg") ?
                    //                        JSON.parse(localStorage.getItem("UserMsg")).extNum ?
                    //                        JSON.parse(localStorage.getItem("UserMsg")).extNum :
                    //                        "" : ""
                },
                formManagement: {
                    user: "",
                    password: ""
                },
                GROUP_USER: "",
                single: false,
                agentRules: {
                    user: [{
                        required: true,
                        message: "请输入工号",
                        trigger: "blur"
                    }],
                    password: [{
                        required: true,
                        message: "请输入密码",
                        trigger: "blur"
                    }]
                },
                manageRules: {
                    manageuser: [{
                        required: false,
                        message: "请输入工号",
                        trigger: "blur"
                    }],
                    managepassword: [{
                        required: false,
                        message: "请输入密码",
                        trigger: "blur"
                    }]
                },
                loading2: false,
                extnumShow: false
            };
        },
        methods: {
            isExtnumShow() {
                //      var _this = this;
                //      var contactDetail = {
                //        auth: "",
                //        group: "csr",
                //        method: "mbapp.queryAgentType",
                //        params: { userId: _this.formAgent.user },
                //        version: "1.0"
                //      };
                //      _this
                //        .$ajax({
                //          method: "POST",
                //          baseURL: _this.$ajax.defaults.baseURLcc,
                //          url: "mbapp/queryAgentType",
                //          data: JSON.stringify(contactDetail)
                //        })
                //        .then(function(res) {
                //          if (res.data.code == "20000") {
                //            if (res.data.result.AGENT_TYPE != "MultiMedia") {
                //              _this.agentRules.extnum = [
                //                { required: true, message: "请输入密码", trigger: "blur" }
                //              ];
                //              _this.extnumShow = true;
                //            } else {
                //              delete _this.agentRules.extnum;
                //              _this.extnumShow = false;
                //            }
                //          }
                //        });
            },
            goto() {
                var _this = this;
                _this.loading2 = true;

                _this.$refs["formManagement"].validate(function(valid) {
                    if (!valid) {
                        _this.$Message.error("座席端登录失败!");
                        _this.loading2 = false;
                    } else {
                        $.ajax({
                            url: _this.ManloginURL,
                            type: "post",
                            data: {
                                userId: _this.formManagement.user,
                                passwd: _this.formManagement.password
                            },
                            dataType: "json",
                            success: function(result) {
                                console.log(result)
                                window.location.href =
                                    'http://192.168.6.80/ifly_cem_oms/portal.html'
                                    // "http://192.168.6.80/ifly_cem_oms/portal.html?userId="+_this.formManagement.user+"&token="+_this.formManagement.password;

                            },
                            error: function(xhr) {
                                console.log(xhr)
                            }
                        });
                        // _this.loginManage(_this.formManagement.user, _this.formManagement.password)

                    }
                });
            },
            loginBtn() {
                var _this = this;
                this.loading2 = true;

                this.$refs['formAgent'].validate(function(valid) {
                    if (!valid) {
                        _this.$Message.error('登录失败!');
                        _this.loading2 = false;
                    } else {
                        _this.login_goto(_this.formAgent.user, _this.formAgent.password)

                    }
                });

            },
            //账号密码错误
            //            loginCallback(status) {
            //                 this.$Message.error('账号密码错误请重新登陆');
            //                 this.loading2 = false;
            //            },
            //登陆管理端
            async loginManage(name, pwd) {
                debugger;
                let _this = this;
                let jsondata = await loginService.loginManage({
                    'userId': name,
                    'passwd': pwd
                })
                console.log(jsondata);
                if (jsondata.message == '您的工号输入有误') {
                    this.$Message.error('账号密码错误请重新登陆');
                    this.loading2 = false;
                } else {
                    _this.loading2 = false;
                    _this.$Message.success("登录成功!");
                    window.location.href =
                        'http://192.168.6.80/ifly_cem_oms/'
                        // "http://192.168.6.80/ifly_cem_oms/portal.html?userId="+_this.formManagement.user+"&token="+_this.formManagement.password;
                }
            },
            //登陆反回
            async login_goto(name, pwd) {
                let jsondata = await loginService.login_goto({
                    'userId': name,
                    'passwd': pwd,

                }, this.loginCallback)

            if (jsondata.message == '用户名或密码错误') {
                    this.$Message.error('账号密码错误请重新登陆');
                    this.loading2 = false;
                } else {
                localStorage.setItem('username', name);
                localStorage.setItem('userpwd', pwd);
                    this.getStateHome(name);
                    this.$store.dispatch('getRoleList', {
                        'userId': name
                    })
                    localStorage.setItem('UserID', name);
                  console.log(jsondata);
                  console.log(jsondata.userId);
                localStorage.setItem('UserID', jsondata);
                  this.$store.dispatch('setLoginUserInfo', {
                    "userId": jsondata.userId, //登陆人ID
                    "curHandlerGroupId": jsondata.skillCode, // 操作人所属组ID
                    "curHandlerGroupName": jsondata.skillName, // 操作人所属组名字
                    "curHandlerName": jsondata.userName, // 操作人（登陆人）名字
                    "curHandlerId": jsondata.voiceAgentId // 操作人工号
                  })
                    // this.user_info();
                    //                   sessionStorage.setItem('sessId',123)

                    jsCookie.set('sessId', '111')
                        //                   cookie.setItem('sunnyDayCookie',1)
                }
            },
            //获取用户列表
            async getStateHome(id) {
                let jsondata = await loginService.stateHome({
                    userId: id
                });
                this.GROUP_USER = jsondata.roleCodeList;
                var that_ = this;
                if (that_.GROUP_USER.length > 0) {
                    var flag_user;
                    for (var i = 0; i < that_.GROUP_USER.length; i++) {
                        if (that_.GROUP_USER[i].search("GROUP_MEMBER") != -1) {
                            // 组员
                            flag_user = true;
                            that_.$store.dispatch('updateMenulist', {
                                'userId': that_.formAgent.user
                            });
                            that_.$store.dispatch('getOpenedList');
                        } else if (that_.GROUP_USER[i].search("GROUP_LEADER") != -1) {
                            // 组长
                            flag_user = true;
                            that_.$store.dispatch('updateMenulist', {
                                'userId': that_.formAgent.user
                            });
                            that_.$store.dispatch('getOpenedList');
                        } else if (that_.GROUP_USER[i].search("GROUP_MANAGER") != -1) {
                            // 值班经理
                            flag_user = true;
                            that_.$store.dispatch('updateMenulist', {
                                'userId': that_.formAgent.user
                            });
                            that_.$store.dispatch('getOpenedList');
                        }
                    }
                    if (!flag_user) {
                        localStorage.removeItem("pageOpenedList");
                        that_.$Message.info('当前用户没有坐席权限');
                        that_.loading2 = false;
                    } else {
                        that_.$router.push({
                            path: "/home"
                        });
                    }
                } else {
                    localStorage.removeItem("pageOpenedList");
                    that_.$Message.info('当前用户没有坐席权限');
                    that_.loading2 = false;
                    // that_.$router.push({
                    //     path: "/"
                    // });

                }

            },
            //获取用户信息
            // async user_info() {
            //     let jsondata = await loginService.user_info({
            //
            //     })
            //     console.log(jsondata);
            //     this.$store.dispatch('setLoginUserInfo', {
            //             'userId': jsondata.principal.username, //登陆人ID
            //             "curHandlerGroupId": jsondata.principal.organCode, // 操作人所属组ID
            //             "curHandlerGroupName": jsondata.principal.organName, // 操作人所属组名字
            //             "curHandlerName": jsondata.principal.nickName, // 操作人（登陆人）名字
            //             "curHandlerId": jsondata.principal.username // 操作人工号
            //         })
            //         //设置公号与分机号
            //     var userEntity = {
            //         voiceAgentId: jsondata.principal.agentNo,
            //         extNum: jsondata.principal.extNo,
            //         userName: jsondata.principal.username,
            //     };
            //     localStorage.setItem('UserMsg', JSON.stringify(userEntity));
            //     console.log(localStorage.getItem('UserMsg'));
            //
            //
            // },
            async logout() { //当直接打login地址 退出登陆状态
                await loginService.logout({})
            }
            //         exissessID(){
            //              let _this = this
            //              if(sessionStorage.getItem('sunnyDayCookie')==1){
            //                _this.$Message.error('当前已有用户登陆');
            //                _this.$router.push({
            //                  path: "/1234123"
            //                })
            //              }
            //         }
        },
        mounted() {
            //              this.exissessID()
            var _this = this;
            $(document).keydown(function(e) {
                if (!e)
                    e = window.event;
                if ((e.keyCode || e.which) == 13) {
                    if ($(".ivu-tabs-tab").eq(1).hasClass("ivu-tabs-tab-active")) {
                        _this.goto();
                    } else {
                        _this.loginBtn();
                    }

                }
            })
            localStorage.removeItem("USER_TYPE");
            localStorage.removeItem("pageOpenedList");
            // this.logout()
          // console.log(localStorage.getItem(UserID));
          //
          // var UserID= this.getStateHome(localStorage.getItem('UserID'))
          //
          // if(UserID!=''){
          //   this.$store.dispatch('setLoginUserInfo', {
          //     "userId": UserID.userId, //登陆人ID
          //     "curHandlerGroupId": UserID.skillCode, // 操作人所属组ID
          //     "curHandlerGroupName": UserID.skillName, // 操作人所属组名字
          //     "curHandlerName": UserID.userName, // 操作人（登陆人）名字
          //     "curHandlerId": UserID.voiceAgentId // 操作人工号
          //   })
          // }



        }
    };
</script>

<style scoped>
    .login-box {
        position: relative;
        height: 100%;
        background-position: center center;
        background-size: cover;
        background-image: url("../../assets/img/login.jpg");
        background-repeat: no-repeat;
    }
    
    .agrnt-login {
        width: 400px;
        height: 365px;
        position: absolute;
        left: 75%;
        top: 50%;
        margin-top: -182px;
        margin-left: -200px;
        background-color: rgba(255, 255, 255, 0.5);
        border-radius: 5px;
    }
    
    .mobike {
        width: 210px;
        height: 40px;
        position: absolute;
        left: 75%;
        top: 50%;
        margin-left: -106px;
        margin-top: -256px;
        background-size: 100% 100%;
        background-image: url("../../assets/img/logo.png");
        background-repeat: no-repeat;
    }
    
    .login-form {
        width: 295px;
        margin: 0 auto;
        margin-top: 44px;
    }
</style>
<style>
    .login-box .ivu-tabs-nav {
        width: 100% !important;
    }
    
    .login-box .ivu-tabs-tab {
        width: 50% !important;
        padding: 0px 0px 23px 0px !important;
        text-align: center;
        color: #1b1b1b !important;
        font-size: 18px !important;
        font-weight: 800;
    }
    
    .login-box .ivu-tabs-nav .ivu-tabs-tab:hover {
        color: #da3c27 !important;
    }
    
    .login-box .ivu-tabs-ink-bar {
        background-color: #fe8710 !important;
    }
    
    .login-box .ivu-btn-error {
        background-color: #f05d49;
        border-color: #f05d49;
    }
    
    .login-box .ivu-btn.ivu-btn-error.ivu-btn-long {
        font-size: 18px;
        font-weight: 800;
    }
    
    .login-box .ivu-input:focus {
        box-shadow: 0 0 0 2px rgba(248, 161, 149, 0.2) !important;
    }
    
    .login-box .ivu-input:focus,
    .ivu-input:hover {
        border-color: #f16543 !important;
    }
</style>